import os
import re

# 需要通过指定的文本模式去检查字符串的开头或者结尾，比如文件名后缀，URL，Scheme等等
def demo_1():
    filename = 'spam.txt'
    flag_1 = filename.endswith('.txt')
    print(flag_1)
    flag_2 = filename.startswith('file:')
    print(flag_2)
    url = 'http://www.python.org'
    flag_3 = url.startswith('http:')
    print(flag_3)

    # 如果想检查多种匹配可能，只需要将所有的匹配项放入到一个元组中
    filenames = os.listdir('../temp')
    print(filenames)
    # 过滤出后缀为.txt或.data
    check_result = [name for name in filenames if name.endswith(('.txt', '.data'))]
    print(check_result)
    # 检查是否存在后缀为.py的文件
    check_flag_1 = any(name.endswith('.py1') for name in filenames)
    print(check_flag_1)
    check_flag_2 = any(name.endswith('.py') for name in filenames)
    print(check_flag_2)

# 使用正则去实现匹配字符串开头
def demo_2():
    url = 'http://www.python.org'
    flag = re.match('http:|https:|ftp:', url)
    print(flag)

# 普通数据聚合相结合
def demo_3():
    filenames = os.listdir('../temp')
    if any(name.endswith(('.txt', '.data')) for name in filenames):
        print("have file end with .txt or .data")

if __name__ == '__main__':
    # demo_1()
    # demo_2()
    demo_3()